package io.xjar.boot;

import io.xjar.XLauncher;
import io.xjar.XPluginManager;
import io.xjar.key.XKey;
import org.springframework.boot.loader.launch.WarLauncher;

import java.io.File;
import java.net.URL;
import java.util.Collection;

/**
 * Spring-Boot War 启动器
 *
 * @author Payne 646742615@qq.com
 * 2018/11/23 23:06
 */
public class XWarLauncher extends WarLauncher {
    private final XLauncher xLauncher;

    public XWarLauncher(String... args) throws Exception {
        this.xLauncher = new XLauncher(args);
    }

    public static void main(String[] args) throws Exception {
        new XWarLauncher(args).launch();
    }

    public void launch() throws Exception {
        // 初始化插件管理器
        XPluginManager pluginManager = new XPluginManager(
                new File("plugins"), 
                this.getClass().getClassLoader(), 
                xLauncher.xDecryptor, 
                xLauncher.xEncryptor, 
                xLauncher.xKey);
        
        // 加载插件
        try {
            pluginManager.loadPlugins();
            System.out.println("插件加载完成，共加载 " + pluginManager.getPlugins().size() + " 个插件");
        } catch (Exception e) {
            System.err.println("插件加载失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        launch(xLauncher.args);
    }

    @Override
    protected ClassLoader createClassLoader(Collection<URL> urls) throws Exception {
        return new XBootClassLoader(urls.toArray(new URL[]{}), this.getClass().getClassLoader(), xLauncher.xDecryptor, xLauncher.xEncryptor, xLauncher.xKey);
    }

}